<?
$exec_start = exact_millisec();
 
$s  = $_GET["s"];    
$ly = $_GET["ly"];
$lz = $_GET["lz"];
$le = $_GET["le"];
$lo = $_GET["lo"];
$ld = $_GET["ld"];
$ft = $_GET["ft"];
$fo = $_GET["fo"];
$ff = $_GET["ff"];

$pmp_image_name         = $_GET["i"];
$pmp_resize_width       = $_GET["w"];
$pmp_resize_height      = $_GET["h"];
$pmp_break_point        = $_GET["r"];     /* undo/history break point */
$pmp_dropper_x          = $_GET["ex"];
$pmp_dropper_y          = $_GET["ey"]; 
$pmp_font_params        = $_GET["f"];

$pmp_drawing_tool       = $_GET["t"];
$pmp_drawing_data       = $_GET["d"];
$pmp_drawing_pen        = $_GET["p"];
$pmp_drawing_color      = $_GET["c"]; 
$pmp_second_color       = $_GET["c2"];  

$pmp_marquee_x          = $_GET["px"];
$pmp_marquee_y          = $_GET["py"];
$pmp_marquee_w          = $_GET["pw"];
$pmp_marquee_h          = $_GET["ph"];
$pmp_bg_color           = $_GET["bg"];

// command params
$pmp_cmd_log_file       = $_GET["l"];     /* log flag */
$pmp_cmd_brush          = $_GET["b"];     /* brushes flag */
$pmp_cmd_undo           = $_GET["u"];     /* undo flag */
$pmp_cmd_font_list      = $_GET["m"];     /* font list flag */
$pmp_cmd_draw           = $_GET["z"];     /* drawing flag */
$pmp_cmd_metrics        = $_GET["em"];    /* metrics flag */
$pmp_cmd_actual_size    = $_GET["ac"];    /* actual image size flag */
$pmp_cmd_skip_drawing   = $_GET["sd"];    /* skip drawing flag */
$pmp_cmd_new_image      = $_POST["ndn"];  /* new image flag */
 
// new image params
$pmp_new_image_width    = $_POST["ndw"];
$pmp_new_image_height   = $_POST["ndh"];
$pmp_new_image_bgcolor  = $_POST["ndc"];
$pmp_new_image_folder   = $_POST["ndd"];
$pmp_new_image_fullpath = $_POST["ndp"];


if ($pmp_resize_width=="") 
{ // default image width
    $pmp_resize_width = 100; 
}
if ($pmp_image_name=="") 
{ // default image path
    $pmp_image_name = "images/p_ico_default.jpg"; 
}


if ( !(strpos($pmp_image_name, "ttp:")===false) ) 
{ // for remote images load from cache   
	$tmp_arr  = split ("/",$pmp_image_name);
	$file     = $tmp_arr[count($tmp_arr)-1];
	$folder   = $tmp_arr[count($tmp_arr)-2];
	$workcopy = "cache/".$folder."/".$file."_workcopy.PNG"; 
	$metafile = "cache/".$folder."/".$file.".log";  
} else { // local images load from image location
    $workcopy = str_replace(".jpg","",strtolower($pmp_image_name))."_workcopy.PNG";
	$metafile = str_replace(".jpg","",strtolower($pmp_image_name)).".log";
}


/* HACK: replace white with current transparent color */
// ---------------------------------------------------------------------------------' 
$file_content  = implode ('', file ($metafile)); 
$file_content = str_replace("FFFFFF","FF33FF",$file_content);
WriteToFile($metafile, $file_content); 
  
  
// BEGIN script METHODS  
// ================================================================================='

// just print out the log file  
// ---------------------------------------------------------------------------------' 
if ($pmp_cmd_log_file=="log") 
{ 
	$file_content  = implode ('', file ($metafile)); 
    print $file_content;
    exit;
}
// create brushes and images
// ---------------------------------------------------------------------------------' 
else if ($pmp_cmd_brush!="") 
{ 
    createbrush ($pmp_cmd_brush);
} 
// HACK: create a new document and redirect back to edit page
// ---------------------------------------------------------------------------------' 
else if ($pmp_cmd_new_image!="") 
{ 
	$oi = imagecreatetruecolor($pmp_new_image_width,$pmp_new_image_height);
	if ($pmp_new_image_bgcolor=="X") 
	{ 
		$wc = imagecolorallocate($oi, 255,250,255);  
	} 
	else 
	{
		$c1 = colorparse ($pmp_new_image_bgcolor);
		$wc = imagecolorallocate($oi, $c1[0], $c1[1], $c1[2]); 	
	}
    imagefill($oi,0,0,$wc);
         
	header("Content-type: image/jpeg");
	 
	$np=$pmp_new_image_folder."/".$pmp_cmd_new_image.".JPG";
	
	// Display and destroy the image
	imagejpeg($oi,$np,100);
	imagedestroy($oi);  
	 
	print "<script>location.href='index.php?e=e&r=on&efile=".str_replace($pmp_new_image_fullpath,"",$np)."';</script>";   
	exit;   
} 
// create font list image
// ---------------------------------------------------------------------------------' 
else if (strlen($pmp_cmd_font_list)>0) 
{ 
	$oi = imagecreate($pmp_marquee_w,$pmp_marquee_h);
	$wc = imagecolorallocate($oi, 255,51,255); 
	imagecolortransparent($oi,$wc);
	$c1 = colorparse ($pmp_drawing_color);
	$bc = imagecolorallocate($oi, $c1[0], $c1[1], $c1[2]); 
	
	$dirname  = "fonts";
	$real    = realpath($dirname);
	$dh = opendir( $dirname ) or die ("couldn't open directory");  
	$k=10;$j=0;
	while (! ( ( $file = readdir ( $dh ) ) == false ) ) 
	{ 	
	   $abspath   = $real."/".$file; 
		if (! ($file == ".") ) { 
			if ( $file == ".." ) 
			{  
			   // take no action
			} 
			else if (!is_dir ($abspath))  
			{ 
			    if ($j==$pmp_font_params) 
				{
				    imagefttext ($oi,$s,0,4,12,$bc,$abspath,$pmp_cmd_font_list);
				    break;
				} 
				$j++;
			}
		} 
	}
	closedir( $dh );   
	// Create the image resource and assign colors
	 header("Content-type: image/png");
	
	// Display and destroy the image
	imagepng($oi);
	imagedestroy($oi); 
	exit; 
} 
// undo commands 
// ---------------------------------------------------------------------------------' 
else if (strlen($pmp_cmd_undo)>0) 
{ 
	   
	$arr = file_to_array($metafile); 
	$file_content = "";
	for ($e=0;$e<count($arr);$e++) {
		 if (substr($arr[$e],0,4)=="tool") { 
			   if ($e>$pmp_cmd_undo) break; 
			   else {
                   parse_str($arr[$e]);
                   $arr[$e]="tool=".$tool."&color=".$color."&pen=".$pen."&font=".$font."&linedata=".trim($linedata); 
			   }
		 }
		$file_content .= stripslashes($arr[$e])."\n";
	} 
	 
	print $file_content;
	unlink($workcopy);
	WriteToFile($metafile, $file_content); 
	exit; 
}  

 
// START
// ================================================================================='

// open image and read size values
// ---------------------------------------------------------------------------------'
if (strlen($pmp_break_point)>0) 
{ // for undo commands, load the SOURCE image
    $input_image  = @imagecreatefromfile($pmp_image_name); 
	$size_of_image = imagegetdims($pmp_image_name); 
} 
else if (file_exists($workcopy)) 
{ // use the WORKCOPY image if one is available
    /* DEBUG DATA */ addmetric ("Opening workcopy");
    $input_image  = @imagecreatefrompng($workcopy); 
	$size_of_image = getimagesize($workcopy); 
    /* DEBUG DATA */ addmetric ("workcopy open");
} 
else 
{ // if no WORKCOPY is available, use the SOURCE image
	/* DEBUG DATA */ addmetric ("Opening original file");
	$input_image  = @imagecreatefromfile($pmp_image_name); 
	/* DEBUG DATA */ addmetric ("getting image size");
	$size_of_image = array(imagesx($input_image),imagesy($input_image)); 
	/* DEBUG DATA */ addmetric ("done getting image size");
}

// if the image fails to load, create an error message image
// ---------------------------------------------------------------------------------'
if ($input_image=="") 
{ 
   $input_image = imagecreate($pmp_resize_width,$pmp_resize_width); 
   $wc = imagecolorallocate($input_image, 255, 250, 250); 
   $gc = imagecolorallocate($input_image, 200, 200, 200); 
   $bc = imagecolorallocate($input_image, 66, 99, 250); 
   $rc = imagecolorallocate($input_image, 255, 99, 99); 
   imagestring( $input_image,3, 2, 2,"ERROR!",$rc);   
   imagestring( $input_image,1, 2, 14,"Unable to open",$bc);   
   border ($input_image,0,0,$pmp_resize_width-1,$pmp_resize_width-1,$bc,$bc); 			
    
   
   $error_string_x = 2;
   $error_string_y = 28;
   for ($z=0;$z<strlen($pmp_image_name);$z++) 
   {
	   $c=substr($pmp_image_name,$z,1); 
	   imagestring( $input_image,1, $error_string_x+1, $error_string_y+1,$c,$gc);
	   imagestring( $input_image,1, $error_string_x, $error_string_y,$c,$bc);
	   $error_string_x += imagefontwidth(1);
	   if ($error_string_x>=$pmp_resize_width-5) 
	   {
		  $error_string_x=2;
		  $error_string_y+= 10;
	   }
   } 
   $size_of_image = array($pmp_resize_width,$pmp_resize_width); 
}  	



// return actual image size if requested	
// ---------------------------------------------------------------------------------'
if (strlen($pmp_cmd_actual_size)>0) 
{ 
	print $size_of_image[0].",".$size_of_image[1];
	exit;
}	 


if (strlen($pmp_resize_height)>0) 
{ 
    $image_ratio = $pmp_resize_height/$size_of_image[1];
}	 

// BEGIN writing to image metafile
// ================================================================================='
if (strlen($pmp_cmd_draw)>0)  
{ 
    /* DEBUG DATA */ addmetric ("inserting commands");
	if (strlen($pmp_font_params)>0) { // TO DO:come up with better font control
		$correctedfont   = split(" ",$pmp_font_params);
		$pmp_font_params = $correctedfont[0] ." ". floor($correctedfont[1]/$image_ratio);
	} 
	
	$coords_list   = explode('/', $pmp_cmd_draw);   
	$file_content  = implode('', file($metafile));
	if ($pmp_drawing_pen==0) 
	{
	    $pmp_drawing_pen=10;
	} 
	$line_color    = $pmp_second_color==""?$pmp_drawing_color:$pmp_second_color;
	$file_content .= "tool=$pmp_drawing_tool&color=$line_color&pen=$pmp_drawing_pen&font=$pmp_font_params&linedata=$pmp_drawing_data\n";
	if ($pmp_drawing_data!="") 
	{
		$coords_list = array($pmp_drawing_data); 
	}
	for ($e=0;$e<count($coords_list);$e++) 
	{
		$coordinate = split (',', $coords_list[$e]); 
		
		// all data is factored by ratio between actual and displayed image size
		$current_line = "";
		if ($pmp_drawing_data=="") 
		{
			$current_line = floor($pmp_drawing_pen/$image_ratio); // pen size
		}
		
		// add line coords 
		for ($o=0;$o<count($coordinate);$o++) 
		{
			$current_line .= ($current_line==""?"":","). (is_numeric($coordinate[$o])?$coordinate[$o]/$image_ratio:$coordinate[$o]) ; 
		} 
		
		$file_content .=  stripslashes($current_line)."\n";
	} 
	
	print $file_content;
		
	WriteToFile($metafile, $file_content); 
	exit;

} 
// END writing to image metafile
// ================================================================================='
 
 
$transparent_color   = imagecolorallocate($input_image, 255,51,255); /* set transparent color */ 
$lasso_list          = array();
$lasso_color         = array();
$cropped_image_size  = array();
$number_of_tools     = 0; 
$file_content        = "";
$can_save_copy       = 0; 

imagecolortransparent ($input_image, $transparent_color);
/* DEBUG DATA */ addmetric ("writing metafile data");

// BEGIN drawing from image metafile
// ================================================================================='
if (file_exists($metafile)&&strlen($pmp_cmd_skip_drawing)==0) { // write any metafile data 
    $bg  = imagecolorallocate($input_image, 255, 255, 0);   
     
	$dots = file_to_array($metafile); // split('\n',$off); 
	for ($z=0;$z<count($dots);$z++) 
	{
		
		 // stop adding when a break point is reached
		 if ((strlen($pmp_break_point)>0)&&($pmp_break_point<0)) 
		 {
		     break;  
		 }
		 	  
		 $current_line = $dots[$z]; 
		 $number_of_tools ++;
		 $dot = split (',', $dots[$z]);
		 if (substr($dots[$z],0,4)=="tool") 
		 { // tool marker
		 
		    $linedata   = "";
			$layerindex = "";
			$marked     = "";
			parse_str($dots[$z]);
		    
			if (trim($marked)=="") 
			{ // if this tool hasnt been marked then set it as marked
			    $current_line="tool=".$tool."&color=".$color."&pen=".$pen."&font=".$font."&linedata=".trim($linedata)."&layerindex=".trim($layerindex)."&marked=marked";
				/* DEBUG DATA */ addmetric ("drawing ".$tool."(".$number_of_tools.")");
				$can_save_copy = 1;
			} 
			
			$number_of_tools = 0;
			
			if ($color=="") 
			{ // default to transparent color
			    $color = $transparent_color;
			}
			else 
			{ 
				$c1 = colorparse ($color);
				$color = imagecolorallocate($input_image, $c1[0], $c1[1], $c1[2]); 
			}
			
			if (count($lasso_list)>0) 
			{ // draw lassos after end of coordinate list
				$temp_alpha_rgb = imagecolorallocate($input_image,$lasso_color[0],$lasso_color[1],$lasso_color[2]);  
				imagefilledpolygon ($input_image,$lasso_list,count($lasso_list)/2, $temp_alpha_rgb);  
				$lasso_list = array();
			}
			
			if ($tool=="Lasso") 
			{ 
			     if ($linedata=="") 
				 { // default lasso color to tool color
				     $lasso_color = $c1; 
				 }
				 else 
				 {
				     $lasso_color = colorparse ($linedata); 
				 }
			}
		 } 
		 else if (($pmp_break_point=="") && (trim($marked)=="marked")) 
		 { // if this tool has already been marked, just note the new size
		 
			 if ($tool=="Crop") 
			 { 
			     if (count($dot)>3) 
				 { 
					 $cropped_image_size  = array($dot[2],$dot[3]); 
				 }
			 } 
			 else if ($tool=="Rotate") 
			 { 
				 $cropped_image_size  = imagegetdims($input_image); 
			 }  
			 else if ($tool=="Scale") 
			 {  
				 $cropped_image_size  = imagegetdims($input_image); 
			 } 
		 } 
		 else if (count($dot)>0) 
		 {  // draw from coordinates
			 if ($tool=="Bucket") 
			 { // bucket fill draws a rectangle
			     if (count($dot)>3) 
				 {
				     @imagefilledrectangle($input_image,$dot[0],$dot[1],$dot[2],$dot[3],$color); 		
				 }
			 } 
			 else if ($tool=="Lasso") 
			 { // lasso adds coords to lasso list for drawing later
			     array_push($lasso_list, $dot[1], $dot[2]); 
			 } 
			 else if ($tool=="Crop") 
			 { // crop creates a new image and copies the source image to it
				if (count($dot)>3) 
				{ 
					$dx=$dot[0];$dy=$dot[1];$dw=$dot[2];$dh=$dot[3];   
					$cropped_image_size = array($dw,$dh);
					$temp_picture       = imagecreatetruecolor($dw,$dh);  
					$temp_alpha_rgb     = imagecolorallocate($temp_picture, 255,51,255);   
					imagefill($temp_picture,0,0,$temp_alpha_rgb);
					imagecopyresized($temp_picture,$input_image,0,0,$dx,$dy,$dw,$dh,$dw,$dh);  
					// imagecopymerge($temp_picture,$input_image,0,0,$dx,$dy,$dw,$dh,100);  
					imagedestroy($input_image);
					$input_image = $temp_picture;   
				} 
			 } 
			 else if ($tool=="Rect") 
			 { // draws a rectangle 
				 if (strpos($linedata,",")>0) 
				 { 
					$coords_list = split(",",$linedata);  
					imagefilledrectangle($input_image,$coords_list[0],$coords_list[1],$coords_list[2],$coords_list[3],$color); 	
			     }
			 } 
			 else if ($tool=="Line") 
			 { // draws a line
				 if (strpos($linedata,",")>0) 
				 { 
					$coords_list = split(",",$linedata);  
					imageline($input_image,$coords_list[0],$coords_list[1],$coords_list[2],$coords_list[3],$color); 	
			     }
			 }  
			 else if ($tool=="Oval") 
			 { // draws an oval 
				 if (strpos($linedata,",")>0) 
				 { 
					$coords_list = split(",",$linedata);  
					imagefilledellipse($input_image,$coords_list[0],$coords_list[1],$coords_list[2],$coords_list[3],$color); 	
			     }
			 } 
			 else if ($tool=="Scale") 
			 {
				$coords_list = array();
				if (strpos($linedata," ")>0) 
				{ 
					$coords_list = split(" ",$linedata); 
					$sc_type=$coords_list[0];$sc_align=$coords_list[1];$sc_scale=$coords_list[2];$sc_siz1=$coords_list[3];$sc_siz2=$coords_list[4];
					
					$cropped_image_size = split("/", $sc_siz1); 
					$temp_picture       = imagecreatetruecolor($cropped_image_size[0],$cropped_image_size[1]);  
					$temp_alpha_rgb     = imagecolorallocate($temp_picture, 255,51,255);   
					imagefill($temp_picture,0,0,$temp_alpha_rgb);
					
					
					if ($sc_type==0) 
					{ // resize canvas
					    $src_x = 0;
						$src_y = 0; 
						if (($sc_align=="C")||($sc_align=="N")||($sc_align=="S")) 
						{
							$src_x = ($cropped_image_size[0]-$size_of_image[0])/2;
							if ($src_x<0) 
							{
								$src_x=0;							  
							}
						} 
						else if (($sc_align=="NE")||($sc_align=="E")||($sc_align=="SE")) 
						{
							$src_x = ($cropped_image_size[0]-$size_of_image[0]);
							if ($src_x<0) 
							{
								$src_x=0;							  
							}
						}  
						
						if (($sc_align=="E")||($sc_align=="C")||($sc_align=="W")) 
						{
							$src_y = ($cropped_image_size[1]-$size_of_image[1])/2;
							if ($src_y<0) 
							{
								$src_y=0;							  
							}
						} 
						else if (($sc_align=="SW")||($sc_align=="S")||($sc_align=="SE")) 
						{
						    $src_y = ($cropped_image_size[1]-$size_of_image[1]);
						    if ($src_y<0) 
							{
							    $src_y=0;			
							}				  
						}  
						
						imagecopymerge($temp_picture,$input_image,$src_x,$src_y,0,0,$size_of_image[0],$size_of_image[1],100);   
					} 
					else 
					{ // resize image
					    imagecopyresampled($temp_picture,$input_image,0,0,0,0,$cropped_image_size[0],$cropped_image_size[1],$size_of_image[0],$size_of_image[1]);   
					}
					imagedestroy ($input_image);		
					$input_image = $temp_picture;   
				 }	  
			 } 
			 else if ($tool=="Rotate") 
			 {
				 $coords_list = array();
				 if (strpos($linedata,",")>0) 
				 { // image rotate
					$coords_list  = split(",",$linedata);  
					$input_image  = imagerotate($input_image, $coords_list[0]*$coords_list[1], $transparent_color);	
					imagecolortransparent($input_image, $transparent_color);  
					$cropped_image_size  = imagegetdims($input_image); 
				 } 
				 else if ($linedata=="FH") 
				 { // horizontal flip
				     $input_image = imageflip($input_image);
				 } 
				 else if ($linedata=="FV") 
				 { // vertical flip
				     $input_image = imageflip($input_image,"FV");
				 }
			} 
			else if ($tool=="Text") 
			{ // text tool NOTE: this needs LOTS of work
				$font = split(" ",$font); 
				imagefttext ($input_image,$font[1],0,$dot[0]+6,$dot[1]+16,$color,fontindex($font[0]),$dot[2]); 
		    } 
			else if ($tool=="Filter") 
			{ // filters  
				$ox=split(" ",$dots[$z]);
				if (count($ox)>1) 
				{
					$l=$ox[0];
					$v=$ox[1];
					if ($l==0) imagefilter($input_image, IMG_FILTER_NEGATE);   
					if ($l==1) imagefilter($input_image, IMG_FILTER_GRAYSCALE);   
					if ($l==2) imagefilter($input_image, IMG_FILTER_BRIGHTNESS,$v	);   
					if ($l==3) imagefilter($input_image, IMG_FILTER_CONTRAST,$v	);      
					if ($l==4) 
					{
						$r=substr($v,0,2);
						$g=substr($v,2,2);
						$b=substr($v,4,2);
						$r=base_convert($r, 16, 10);
						$b=base_convert($b, 16, 10);
						$g=base_convert($g, 16, 10);
						imagefilter($input_image, IMG_FILTER_COLORIZE,$r,$g,$b	);    
					} 
					if ($l==5) imagefilter($input_image, IMG_FILTER_EDGEDETECT,$v	);  
					if ($l==6) imagefilter($input_image, IMG_FILTER_EMBOSS,$v	);  
					if ($l==7) imagefilter($input_image, IMG_FILTER_GAUSSIAN_BLUR,$v	);  
					if ($l==8) imagefilter($input_image, IMG_FILTER_MEAN_REMOVAL,$v	);      
					if ($l==9) imagefilter($input_image, IMG_FILTER_SMOOTH,$v	);      
				}   	
			 } 
			 else if ($tool=="Wand") 
			 {
			     imagefill($input_image, $dot[1],$dot[2], $color);   
			 } 
			 else if ($tool=="Move") 
			 {
			       if (count($dot)>3) 
				   {
				      $ox=$dot[0];$oy=$dot[1];$dx=$dot[2];$dy=$dot[3];$dw=$dot[4];$dh=$dot[5];
					  $moved_portion = imagecreatetruecolor($dw,$dh); 
	                  imagecopymerge($moved_portion,$input_image,0,0,$ox,$oy,$dw,$dh,100); 
					  imagefilledrectangle($input_image,$ox,$oy,$ox+$dw,$oy+$dh,$transparent_color); 	
	                  imagecopymerge($input_image,$moved_portion,$dx,$dy,0,0,$dw,$dh,100);    
				   }
			 } 
			 else 
			 {
			     if ($dot[0]==1) 
				 {
				     imagesetpixel($input_image,$dot[1],$dot[2],$color);  
			     } 
				 else if ($dot[0]>2)
				 {
				     imagefilledellipse($input_image,$dot[1],$dot[2],$dot[0],$dot[0],$color); 	 					 
				 }
			     else 
				 {
				     imagefilledrectangle($input_image,$dot[1]-($dot[0]/2),$dot[2]-($dot[0]/2),$dot[1]+($dot[0]/2),$dot[2]+($dot[0]/2),$color); 	
				 }	 
			 }
		}
		$file_content.=$current_line."\n";
	}
	if ($pmp_break_point=="")
	{
	    WriteToFile($metafile, $file_content); 
	}
	else 
	{
	    $can_save_copy = 0; 
	} 
} 

if (count($lasso_list)>0) 
{ // draw any remaining lassos
	$temp_alpha_rgb = imagecolorallocate($input_image,$lasso_color[0],$lasso_color[1],$lasso_color[2]);  
	imagefilledpolygon ($input_image,$lasso_list,count($lasso_list)/2,$temp_alpha_rgb);  
}

// END drawing from image metafile
// ================================================================================='
 
/* DEBUG DATA */ addmetric ("tools finished (".$number_of_tools.")");
 


if (count ($cropped_image_size )>0) 
{ // reset image size if image has been cropped or resized
    $size_of_image=$cropped_image_size ;
} 


// eye dropper results 
// ---------------------------------------------------------------------------------'
if (strlen($pmp_dropper_x)>0) 
{ 
	$rgb = imagecolorat ($input_image,$pmp_dropper_x/$image_ratio,$pmp_dropper_y/$image_ratio );
	
	$r = ($rgb >> 16) & 255;
	$g = ($rgb >> 8) & 255;
	$b = $rgb & 255;
	$r=base_convert($r, 10, 16);
	$b=base_convert($b, 10, 16);
	$g=base_convert($g, 10, 16);
	print strtoupper($r.$g.$b);
	exit;
}



// BEGIN resizing image
// ================================================================================='

// determine new image size
// ---------------------------------------------------------------------------------'

$actual_image_width  = $size_of_image[0];
$actual_image_height = $size_of_image[1];

$image_ratio         = $pmp_resize_height / $actual_image_height; // sizing ratio 
$width_to_height     = $actual_image_width / $actual_image_height;  
$new_image_height    = $pmp_resize_width / $width_to_height; // resize by width

if ($actual_image_height>$actual_image_width) 
{ // resize by height if taller
	$new_image_height  = $pmp_resize_width;
	$pmp_resize_width  = $width_to_height * $new_image_height;
}

if (strlen($pmp_resize_height)>0) 
{ // resize by height if specified
     
	$new_image_height = $pmp_resize_height=="X"?$actual_image_height:$pmp_resize_height;
	$pmp_resize_width = $width_to_height * $new_image_height;
}


/* DEBUG DATA addmetric ("creating output image"); */

/*
// create temporary TRANSPARENT image to copy the image onto 
// ---------------------------------------------------------------------------------'
$output_image      = imagecreatetruecolor($actual_image_width,$actual_image_height);  
$transparent_color = imagecolorallocate($output_image, 255,51,255);    
imagefill($output_image, 0, 0, $transparent_color);
imagecolortransparent($output_image, $transparent_color); 
  
// copy the input image onto the TRANSPARENT output image to preserve transparency
// ---------------------------------------------------------------------------------'
imagecopymerge($output_image,$input_image,0,0,0,0,$actual_image_width,$actual_image_height,100);
*/ 
 $output_image=$input_image;
// save a work copy of the image
// ---------------------------------------------------------------------------------'
if ($can_save_copy==1) 
{ 
    /* DEBUG DATA */ addmetric ("saving workcopy"); 
	imagepng($output_image, $workcopy);
}  

/* DEBUG DATA */ addmetric ("creating new image");

$output_image     = imagecreatetruecolor($pmp_resize_width, $new_image_height);
$transparent_color = imagecolorallocate($output_image, 255,51,255);
$white_color       = imagecolorallocate($output_image, 255,255,255);    
$grid_color        = imagecolorallocate($output_image, 100,100,190);   

if (strlen($pmp_marquee_x)==0) 
{
//	imagefill($output_image,0,0,$transparent_color);  
}
imagecolortransparent($output_image, $transparent_color); 

/* DEBUG DATA */ addmetric ("beginning resize"); 


if (($ff=="")&&($ft!="jpeg")&&strlen($pmp_cmd_skip_drawing)==0) 
{ // draw background grid on image before copying image onto it
	imagefill($output_image,0,0,$white_color);  
	$ox = 0; 
	$gr = 15*$image_ratio;
	if ($gr<10) $gr=10;
	if (strlen($pmp_marquee_x)==0) 
	{
		/* DEBUG DATA */ addmetric ("adding grid"); 
		for ($gy=0;$gy<$new_image_height;$gy+=$gr) 
		{
			for ($gx=0;$gx<$pmp_resize_width;$gx+=$gr*2) 
			{ 
				$rx=(255*($gx/$pmp_resize_width));   
				$bc = imagecolorallocate($output_image, $rx,$rx,$rx);  
				imagefilledrectangle($output_image,$gx+($ox*$gr),$gy,$gx+$gr+($ox*$gr),$gy+$gr,$bc);
				// imagerectangle($output_image,$gx+($ox*$gr),$gy,$gx+$gr+($ox*$gr),$gy+$gr,$grid_color);
			}
			$ox = -($ox-1); 
		}
	} 
} 


if ($ft=="wbmp") 
{	// for wbmp images make a 256-color palette
	$output_image = imagecreate($pmp_resize_width,$new_image_height);
	imagecopyresized($output_image,$output_image,$src_x,$src_y,0,0,$pmp_resize_width,$new_image_height,$actual_image_width,$actual_image_height); 
} 
else if (strlen($pmp_bg_color)>0) 
{  // when background is specified, assume a thumbnail
	
	// find coords to center image on 132 x 132 palette
	$pmp_resize_width = floor($pmp_resize_width);
	$new_image_height = floor($new_image_height);
	$src_x = (132-$pmp_resize_width)/2;
	$src_y = (132-$new_image_height)/2;

    // create 132 x 132 palette 
	$output_image = imagecreatetruecolor(132,132);  
	$pmp_bg_color = colorparse($pmp_bg_color); 		
	$pmp_bg_color = imagecolorallocate($output_image, $pmp_bg_color[0], $pmp_bg_color[1], $pmp_bg_color[2]);  
	imagefill($output_image,0,0,$pmp_bg_color);   
	 
	if ($ff=="") 
	{ // image captions 
		$bc = imagecolorallocate($output_image, 0,0,0);  
		$tc = imagecolorallocate($output_image, 190,190,190);  
		$wc = imagecolorallocate($output_image, 255,255,0); 
		$pc = imagecolorallocate($output_image, 255,51,255); 
		imagestring($output_image,1,11,11,"AVATAR PNG",$bc);
		imagestring($output_image,1,10,10,"AVATAR PNG",$tc);
		imagestring($output_image,1,11,19,filetitle($i),$bc);
		imagestring($output_image,1,10,18,filetitle($i),$tc);
		imagestring($output_image,1,11,27,$pmp_resize_width." x ".$new_image_height,$bc);
		imagestring($output_image,1,10,26,$pmp_resize_width." x ".$new_image_height,$tc);
		
        
		imagecopyresized($output_image,$input_image,$src_x,$src_y,0,0,$pmp_resize_width,$new_image_height,$actual_image_width,$actual_image_height); 
		
		if ( ! file_exists($workcopy) ) 
		{ // caption for unedited images
			imagestring($output_image,1,33,59,"NOT YET EDITED",$bc);
			imagestring($output_image,1,32,58,"NOT YET EDITED",$wc);
		} 
	} 
	else 
	{		
		imagecolortransparent($output_image, $pmp_bg_color); 
		imagecopyresized($output_image,$input_image,$src_x,$src_y,0,0,$pmp_resize_width,$new_image_height,$actual_image_width,$actual_image_height);  
	}  
}  else { 
    /* DEBUG DATA */ addmetric ("copying resized image"); 
	imagecopyresized($output_image,$input_image,0,0,0,0,$pmp_resize_width,$new_image_height,$actual_image_width,$actual_image_height); 
}

 
/* DEBUG DATA */ addmetric ("exchanging images");

$l=$_GET["l"];
$v=$_GET["v"];
if (strlen($l)>0) {
    /* DEBUG DATA */ addmetric ("adding filters");
	if ($l==0) imagefilter($output_image, IMG_FILTER_NEGATE);   
	if ($l==1) imagefilter($output_image, IMG_FILTER_GRAYSCALE);   
	if ($l==2) imagefilter($output_image, IMG_FILTER_BRIGHTNESS,$v	);   
	if ($l==3) imagefilter($output_image, IMG_FILTER_CONTRAST,$v	);      
	if ($l==4) {
	   $r=substr($c,0,2);
	   $g=substr($c,2,2);
	   $b=substr($c,4,2);
		$r=base_convert($r, 16, 10);
		$b=base_convert($b, 16, 10);
		$g=base_convert($g, 16, 10);
		imagefilter($output_image, IMG_FILTER_COLORIZE,$r,$g,$b	);    
	} 
	if ($l==5) imagefilter($output_image, IMG_FILTER_EDGEDETECT,$v	);  
	if ($l==6) imagefilter($output_image, IMG_FILTER_EMBOSS,$v	);  
	if ($l==7) imagefilter($output_image, IMG_FILTER_GAUSSIAN_BLUR,$v	);  
	if ($l==8) imagefilter($output_image, IMG_FILTER_MEAN_REMOVAL,$v	);      
	if ($l==9) imagefilter($output_image, IMG_FILTER_SMOOTH,$v	);      
} 

 
$exec_end = exact_millisec();

/* DEBUG DATA */ addmetric ("done (".($exec_end-$exec_start).")");
if (strlen($pmp_marquee_x)>0) 
{ // render only a marquee of an image fragment
    $im = imagecreate($pmp_marquee_w,$pmp_marquee_h);
	imagecopy($im,$output_image,0,0,$pmp_marquee_x,$pmp_marquee_y,$pmp_marquee_w,$pmp_marquee_h);  
	 
	// Create the image resource and assign colors
	header("Content-type: image/jpeg");
	
	// Display and destroy the image
	imagejpeg($im);
	imagedestroy($im);
    exit; 
} 
else 
{ // render image metrics when requested
	$bc = imagecolorallocate($output_image, 55,0,255);
	$tc = imagecolorallocate($output_image, 250,250,250);  
	for ($e=0;$e<count($metrics);$e++) 
	{   
	     //imagestring ($output_image,4,6,11+(12*$e),$metrics[$e],$tc); 
	     //imagestring ($output_image,4,5,10+(12*$e),$metrics[$e],$bc); 
	}
	$i=0;
	$last_x1 = 10;
	$last_y1 = 10;
	while (list($a,$b) = each($arr_metric_data))
	{
	    if ($i>0)
		{
		    $this_x1 = (10 * ($b[0] - $exec_time)) + 10;
			$this_y1 = $last_y1 + 10;
			imageline ($output_image, $last_x1+1, $last_y1+1, $this_x1+1, $this_y1+1, $tc);
			imageline ($output_image, $last_x1, $last_y1, $this_x1, $this_y1, $bc);
			$char_x = $this_x1+16;
			$char_y = $this_y1-8;
			imagestring ($output_image,3,$char_x+1,$char_y+1,$b[1]." (".number_format($b[0] - $exec_time,4).")",$tc); 
			imagestring ($output_image,3,$char_x,$char_y,$b[1]." (".number_format($b[0] - $exec_time,4).")",$bc); 
			$last_x1 =  $this_x1;
			$last_y1 =  $this_y1;
		}
		$exec_time  = $b[0]; 
	    $i++;
	}
}
/*
*/
$types["jpeg"] = "image/jpeg";
$types["gif"]  = "image/gif";
$types["png"]  = "image/png";
$types["wbmp"]  = "image/wbmp";
if ($fo=="") $fo=75;
// Create the image resource and assign colors
// header("Content-type: image/jpeg");


if (strlen($ft)>0) {
    
    header("Content-type: ".$types[$ft]);
	
	if ($ff!="") {
	    header('Content-Disposition: attachment; filename="'.$ff.'"');
	   // $output_image = imagecreatefrompng($workcopy);
	}
	if ($ft=="jpeg")  imagejpeg ($output_image,"",$fo);
	if ($ft=="jpg")   imagejpeg ($output_image,"",$fo);
	if ($ft=="png")   imagepng ($output_image);
	if ($ft=="gif")   imagegif ($output_image);
	if ($ft=="wbmp")  imagewbmp ($output_image);  
	
} else {




	header("Content-type: image/png"); 
	imagepng($output_image);
}


imagedestroy($output_image); 
imagedestroy ($input_image);
exit;
	
	
	
	
	
	
	
	
	
	
	
	
	
// functions
$arr_metric_data = array();
function addmetric ($a) 
{
    global $metrics;
    global $arr_metric_data;
	global $pmp_cmd_metrics;
	list($u,$s) = explode(" ",microtime());
	$b = date("H:i:s");
	if (strlen($pmp_cmd_metrics)>0) 
	{
		$metrics[count($metrics)] =  number_format(exact_millisec(), 4, ".", ",") ." - ".$a; 
		$arr_metric_data[count($arr_metric_data)] =  array (exact_millisec(),$a);  
	}
}	
function exact_millisec() 
{
	list($u,$s) = explode(" ",microtime());
	$s = date("U");
	return $s+$u ;
}

function border ($im,$x1,$y1,$x2,$y2, $c1,$c2) {
	imageline ( $im, $x1, $y1, $x2, $y1, $c1); // n
	imageline ( $im, $x1, $y1, $x1, $y2, $c1); // w
	imageline ( $im, $x2, $y1, $x2, $y2, $c2); // e
	imageline ( $im, $x1, $y2, $x2, $y2, $c2); // s
} 

function imageCopyResampleBicubic($dst_img, $src_img, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h)
{
  $scaleX = ($src_w - 1) / $dst_w;
  $scaleY = ($src_h - 1) / $dst_h;

  $scaleX2 = $scaleX / 2.0;
  $scaleY2 = $scaleY / 2.0;

  $tc = imageistruecolor($src_img);
  
   
		 
  for ($y = $src_y; $y < $src_y + $dst_h; $y++)
  {
   $sY  = $y * $scaleY;
   $siY  = (int) $sY;
   $siY2 = (int) $sY + $scaleY2;

   for ($x = $src_x; $x < $src_x + $dst_w; $x++)
   {
     $sX  = $x * $scaleX;
     $siX  = (int) $sX;
     $siX2 = (int) $sX + $scaleX2;
	 
      

     if ($tc)
     {
       $c1 = imagecolorat($src_img, $siX, $siY2);
       $c2 = imagecolorat($src_img, $siX, $siY);
       $c3 = imagecolorat($src_img, $siX2, $siY2);
       $c4 = imagecolorat($src_img, $siX2, $siY);

       $r = (($c1 + $c2 + $c3 + $c4) >> 2) & 0xFF0000;
       $g = ((($c1 & 0xFF00) + ($c2 & 0xFF00) + ($c3 & 0xFF00) + ($c4 & 0xFF00)) >> 2) & 0xFF00;
       $b = ((($c1 & 0xFF)  + ($c2 & 0xFF)  + ($c3 & 0xFF)  + ($c4 & 0xFF))  >> 2);




       imagesetpixel($dst_img, $dst_x + $x - $src_x, $dst_y + $y - $src_y, $r+$g+$b);
     }
     else
     {
       $c1 = imagecolorsforindex($src_img, imagecolorat($src_img, $siX, $siY2));
       $c2 = imagecolorsforindex($src_img, imagecolorat($src_img, $siX, $siY));
       $c3 = imagecolorsforindex($src_img, imagecolorat($src_img, $siX2, $siY2));
       $c4 = imagecolorsforindex($src_img, imagecolorat($src_img, $siX2, $siY));

       $r = ($c1['red']  + $c2['red']  + $c3['red']  + $c4['red']  ) << 14;
       $g = ($c1['green'] + $c2['green'] + $c3['green'] + $c4['green']) << 6;
       $b = ($c1['blue']  + $c2['blue']  + $c3['blue']  + $c4['blue'] ) >> 2;

       imagesetpixel($dst_img, $dst_x + $x - $src_x, $dst_y + $y - $src_y, $r+$g+$b);
     }
   }
  }
}

function imageflip ($im,$opt="FH") {

			    list($actual_image_width,$actual_image_height) = imagegetdims($im);
	// $actual_image_width=imagesx($im);
	// $actual_image_height=imagesy($im);
	 $nm=imagecreatetruecolor($actual_image_width,$actual_image_height);
	 
	 for($x=0;$x<=$actual_image_width;$x++) {
	  for($y=0;$y<=$actual_image_height;$y++) {
	  
	   $rgb = imagecolorat($im, $opt=="FH"?(($actual_image_width-1)-$x):$x, $opt=="FH"?$y:(($actual_image_height-1)-$y)); 
	   
	    
	   
	   
	    imagesetpixel($nm,$x,$y,$rgb); 
		 
	  }
	 }
	 imagedestroy ($im);
	 return $nm;
}

function filetitle($thepath) { // filetitle
    $v = split ("/",$thepath);
	$v = $v[count($v)-1];
//	$v = count($v)>10?"..."+$v.substr($v.length-10):$v;
	return $v;
} // filetitle


//    Draw an antialiased pixel. This function basically allows x and y to be set as floats.
function imageSetSmoothPixel( $image, $x, $y, $fullColor, $trueColor = true ) {
	$fx = floor( $x );
	$fy = floor( $y );
	$cx = ceil( $x );
	$cy = ceil( $y );
	$xa = $x - $fx;
	$xb = $cx - $x;
	$ya = $y - $fy;
	$yb = $cy - $y;
	if ( $cx == $fx and $cy == $fy ) {
		imageSetSubPixel( $image, $fx, $fy, 0.0, 1.0, $fullColor, $trueColor );
	} else {
		imageSetSubPixel( $image, $fx, $fy, $xa + $ya, $xb + $yb, $fullColor, $trueColor );
		if ( $cy != $fy ) {
			imageSetSubPixel( $image, $fx, $cy, $xa + $yb, $xb + $ya, $fullColor, $trueColor );
		}
		if ( $cx != $fx ) {
			imageSetSubPixel( $image, $cx, $fy, $xb + $ya, $xa + $yb, $fullColor, $trueColor );
			if ( $cy != $fy ) {
				imageSetSubPixel( $image, $cx, $cy, $xb + $yb, $xa + $ya, $fullColor, $trueColor );
			}
		}
	}
}

function imageSetSubPixel( $image, $x, $y, $a, $b, $fullColor, $trueColor = true ) {
	$tempColor = imageColorsForIndex( $image, imageColorAt( $image, $x, $y ) );
	$tempColor[ 'red' ]   = round( $tempColor[ 'red' ]   * $a + $fullColor[ 'red' ]   * $b );
	$tempColor[ 'green' ] = round( $tempColor[ 'green' ] * $a + $fullColor[ 'green' ] * $b );
	$tempColor[ 'blue' ]  = round( $tempColor[ 'blue' ]  * $a + $fullColor[ 'blue' ]  * $b );
	if ( $tempColor[ 'red' ]   > 255 ) $tempColor[ 'red' ]   = 255;
	if ( $tempColor[ 'green' ] > 255 ) $tempColor[ 'green' ] = 255;
	if ( $tempColor[ 'blue' ]  > 255 ) $tempColor[ 'blue' ]  = 255;
	if ( $trueColor ) {
		$newColor = imageColorExactAlpha( $image, $tempColor[ 'red' ], $tempColor[ 'green' ], $tempColor[ 'blue' ], 0 );
	} else {
		if ( imageColorExact( $image, $tempColor[ 'red' ], $tempColor[ 'green' ], $tempColor[ 'blue' ] ) == -1 ) {
			imageColorAllocate( $image, $tempColor[ 'red' ], $tempColor[ 'green' ], $tempColor[ 'blue' ] );
		}
		$newColor = imageColorExact( $image, $tempColor[ 'red' ], $tempColor[ 'green' ], $tempColor[ 'blue' ] );
	}
	imageSetPixel( $image, $x, $y, $newColor );
}



function createbrush ($b) {
    global $p;
    global $c;
	$brushes = array();
	$brushes["Crop"] = "images/clip.gif";
	$brushes["Text"] = "images/text.gif";
	$brushes["Move"] = "images/move.gif";
	$brushes["Zoom"] = "images/zoom.gif";
	
	if ($b=="brushes") {
	    $ci=date("s");
	    if ($c=="") $c="FFFFFF";
	   $oi = imagecreate(180,80);
	   $wc = imagecolorallocate($oi, 255, 255, 250); 
					$c1 = colorparse ($c);
	   $bc = imagecolorallocate($oi, $c1[0], $c1[1], $c1[2]); 
	   $gc = imagecolorallocate($oi, 255, 255, 0); 
	   $nc = imagecolorallocate($oi, 151, 151, 151); 
	   $w = 1; $d=1;
	   for ($i=0;$i<10;$i++) {
		   $x = 20 + (($i%5) * 32);
		   $y = $i>4?52:20;
		   if ($p==$d) imagefilledrectangle($oi,$x-16,$y-16,$x+16,$y+16,$gc);
		   imagefilledellipse ($oi,$x,$y,$w>32?32:$w,$w>32?32:$w,$bc); 
		   imageellipse ($oi,$x,$y,$w>32?32:$w,$w>32?32:$w,$nc	); 
		   imagestring ($oi,1,$x,$y+12,$d,$nc);
		   $w = $i>3?$w+2:$w*2;
		   $d = $i>4?50+(($i-3)*10):$d*2;
	   }
		$d=date("s");
		
		// Create the image resource and assign colors
		 header("Content-type: image/gif");
		
		// Display and destroy the image
		imagepng($oi);
		imagedestroy($oi); 
		exit; 
	} else if ($b=="curve") {
	
	   $oi = imagecreate($p,$p);
					$c1 = colorparse ($c);
	   $bc = imagecolorallocate($oi, $c1[0], $c1[1], $c1[2]); 
	   $nc = imagecolorallocate($oi, 255, 255, 255); 
	  // imagecolortransparent($oi , $nc);
	
	   imagefilledellipse ($oi,$p+1,$p+1,1+$p*2,1+$p*2,$nc); 
	border($oi,0,0,$p-1,$p-1,$bc,$nc );
		// Create the image resource and assign colors
		 header("Content-type: image/gif");
		
		// Display and destroy the image
		imagepng($oi);
		imagedestroy($oi); 
		exit; 
	
	
	} else if ($b=="scaler") {
	   $oi = imagecreate(140,24);
	   $wc = imagecolorallocate($oi, 255, 255, 255);
	   $nc = imagecolorallocate($oi, 0, 0, 100); 
	   $gc = imagecolorallocate($oi, 0, 150, 0); 
	   $bc = imagecolorallocate($oi, 225, 225, 225);  
	   
	   $n=array("25","50","100","160","240","480","720");
	   $k=0;
	   if ($p=="") $p=100;
	   
	   for ($i=0;$i<140;$i+=20) {
	   
	   
	      $f=$p==$n[$k]?2:1;
	      $c=$p==$n[$k]?$gc:$nc;
	   
		  $w=(imagefontwidth($f) * strlen($n[$k]))/2;
	      imagestring ($oi,$f,($i-$w)+13,14,$n[$k],$bc);
	      imagestring ($oi,$f,($i-$w)+12,13,$n[$k],$c);
		  
		//  imageline ($oi,$i,0,$i,24,$nc);
		  
		  
		  
		  if ($p==$n[$k]) {
		     $pts = array($i+6,12,$i+10,8,$i+14,12);
			 imagefilledpolygon($oi,$pts,3,$bc);
			 imagepolygon($oi,$pts,3,$nc);
			 //imageline ($oi,$i+10,12,$i+10,14,$nc);
		  }
		  
		  
		  $k++;
	   }
	   
	   
	   
	   
	   
	   imageline ($oi,0,12,160,12,$nc);
		// Create the image resource and assign colors
		 header("Content-type: image/gif");
		
		// Display and destroy the image
		imagepng($oi);
		imagedestroy($oi); 
		exit; 
	   
	} else if ($b=="Fonts") {
	   $oi = imagecreate(160,600);
	   $wc = imagecolorallocate($oi, 255, 255, 255);
	   $nc = imagecolorallocate($oi, 0, 0, 100); 
	   $bc = imagecolorallocate($oi, 0, 0, 0);  
	   $dirname  = "fonts";
	   $real    = realpath($dirname);
		$dh = opendir( $dirname ) or die ("couldn't open directory");  
		$k=10;$j=0;
		while (! ( ( $file = readdir ( $dh ) ) == false ) ) { 	
		   $abspath   = $real."/".$file; 
			if (! ($file == ".") ) { 
				if ( $file == ".." ) {  
				} else if (is_dir ($abspath)) { 
				} else { 
					if ($j==$f) imagefilledrectangle($oi,0,$k-12,200,$k,$nc);
					imagefttext ($oi,10,0,4,$k,$j==$f?$wc:$bc,$abspath,$file."(".$k.")");
					$k += 16;
					$j++;
				}
			} 
		}
		closedir( $dh );   
		// Create the image resource and assign colors
		 header("Content-type: image/png");
		
		// Display and destroy the image
		imagepng($oi);
		imagedestroy($oi); 
		exit; 
	} if (($b=="tracer")) {
	   $oi = imagecreate($p,$p);
	   $wc = imagecolorallocate($oi, 255, 33, 250); 
	   $gc = imagecolorallocate($oi, 33, 255, 33); 
	
		$c1 = colorparse ($c);
		$bc = imagecolorallocate($oi, $c1[0], $c1[1], $c1[2]); 
					 
	   imagecolortransparent($oi , $wc);
	   
	   imagefilledellipse ($oi,$p/2,$p/2,$p,$p,$bc); 
	   
	   $half=$p/2; 
	   imageline ($oi,$half-4,$half,$half+4,$half,$gc);
	   imageline ($oi,$half,$half-4,$half,$half+4,$gc);
	   
	   
		// Create the image resource and assign colors
		 header("Content-type: image/gif");
		
		// Display and destroy the image
		imagegif($oi,"images/brush.gif");
		imagedestroy($oi); 
		exit; 
	} else if ($brushes[$b]!="") {
	    $oi = imagecreatefromgif($brushes[$b]); 
	   
		// Create the image resource and assign colors
		 header("Content-type: image/gif");
		
		// Display and destroy the image
		imagegif($oi);
		imagedestroy($oi); 
		exit; 
	} else if (($b=="Bar")) {
		$oi = imagecreate(40,4);
		$c1 = colorparse ($c);
		$bc = imagecolorallocate($oi, $c1[0], $c1[1], $c1[2]); 
		
	   
		// Create the image resource and assign colors
		 header("Content-type: image/png");
		
		// Display and destroy the image
		imagepng($oi);
		imagedestroy($oi); 
		exit; 
	} else if (($b=="Pencil")||($b=="Eraser")) {
	   $oi = imagecreate($p,$p);
	   $wc = imagecolorallocate($oi, 255, 255, 250); 
	   $bc = imagecolorallocate($oi, 255, 0, 0);  
	   imagecolortransparent($oi , $wc);
	   
	   imageellipse ($oi,$p/2,$p/2,$p,$p,$bc); 
	   
	   
	   $half=$p/2; 
	   imageline ($oi,$half-4,$half,$half+4,$half,$bc);
	   imageline ($oi,$half,$half-4,$half,$half+4,$bc);
	   
		// Create the image resource and assign colors
		 header("Content-type: image/gif");
		
		// Display and destroy the image
		imagegif($oi);
		imagedestroy($oi); 
		exit; 
	} else { 
	   $p = 12;
	   $oi = imagecreate($p,$p);
	   $wc = imagecolorallocate($oi, 255, 255, 250); 
	   $bc = imagecolorallocate($oi, 0, 0, 0);  
	   imagecolortransparent($oi , $wc);
	   
	   imageline ($oi,0,$p/2,$p,$p/2,$bc);
	   imageline ($oi,$p/2,0,$p/2,$p,$bc);
	   
		// Create the image resource and assign colors
		 header("Content-type: image/png");
		
		// Display and destroy the image
		imagepng($oi);
		imagedestroy($oi); 
		exit; 
	}
 
}


function fontindex($index) {
   $ret = "";
   $dirname  = "fonts";
   $real    = realpath($dirname);
	$dh = opendir( $dirname ) or die ("couldn't open directory");  
	$k=10;$j=0;
	while (! ( ( $file = readdir ( $dh ) ) == false ) ) { 	
	   $abspath   = $real."/".$file; 
		if (! ($file == ".") ) { 
			if ( $file == ".." ) {  
			} else if (is_dir ($abspath)) { 
			} else { 
			    if ($j==$index) {
				    $ret = $abspath;
				    break;
				} 
				$j++;
			}
		} 
	}
	closedir( $dh );  
	return $ret; 
}


function file_to_array($path) { 
   if (file_exists($path)) {
	$file_content  = implode ('', file ($path)); 
	$file_content  = trim ($file_content);
	return explode("\n", $file_content);
   } else return array();
}

function imagegetdims($path) 
{ 
	 /* DEBUG DATA */ addmetric ("reading path ".filetitle($path));
	
	 // get file and folder name
	 $v = split ("/",$path);
	 $file  =$v[count($v)-1];
	 $folder=$v[count($v)-2]; 
	 
	 $former_cache    = "cache/".$folder."/".$file."_pimpc.JPG"; 
	 $cached_image    = "cache/".$folder."/".$file."_cache.JPG";	 
	 if (file_exists($former_cache)) 
	 {
	     unlink ($former_cache);
	 }
	 
	 if (file_exists($cached_image)) 
	 {
	     $size_of_image = getimagesize($cached_image); 
	 } 
	 else 
	 {
	     $size_of_image = getimagesize($path); 
	 }
	 return $size_of_image;
}

function urlinfo($address)
{
    $result = array();
	$HTTP_FLAG = "http://";
	$char_pos_http = strpos($address, $HTTP_FLAG);
	if ( ! ($char_pos_http===false) )
	{
		$url_fragment   = substr ($address, strlen($HTTP_FLAG));
		$char_pos_slash = strpos ($url_fragment, "/");
		if ( ! ($char_pos_slash===false) )
		{
			$url_domain   = substr ($url_fragment, 0, $char_pos_slash);
			$url_fragment = substr ($url_fragment, $char_pos_slash);
			while (substr($url_fragment,0,1)=="/")
			{
				$url_fragment = substr ($url_fragment, 1);
			}
			$url_arr      = explode ("/", $url_fragment);
			$url_filename = $url_arr[count($url_arr)-1];
			$url_path     = str_replace($url_filename, "", $url_fragment);
			
			while (substr($url_path,strlen($url_path)-1,1)=="/")
			{
				$url_path=substr($url_path,0,strlen($url_path)-1);
			} 
			
		} 
		$result = array (
		  "domain"=>$url_domain,
		  "filename"=>$url_filename,
		  "path"=>$url_path 
		  ); 
		   
	}
	return $result;
}

function imagecreatefromfile($path) 
{
	/* DEBUG DATA */ addmetric ("reading path ".filetitle($path));
		
	$icons = array ( "txt"=>"p_ico_txt.jpg",
	                 "mdb"=>"p_ico_mdb.jpg",
	                 "pdf"=>"p_ico_pdf.jpg",
	                 "vbs"=>"p_ico_vbs.jpg",
	                 "js"=>"p_ico_vbs.jpg",
	                 "wav"=>"p_ico_wav.jpg",
	                 "mp3"=>"p_ico_wav.jpg",
	                 "nsv"=>"p_ico_wav.jpg",
	                 "xml"=>"p_ico_xml.jpg",
	                 "xsl"=>"p_ico_xml.jpg",
	                 "xdr"=>"p_ico_xml.jpg",
	                 "rar"=>"p_ico_zip.jpg",
	                 "zip"=>"p_ico_zip.jpg",
	                 "asp"=>"p_ico_asp.jpg",
	                 "doc"=>"p_ico_doc.jpg",
	                 "htm"=>"p_ico_htm.jpg",
	                 "html"=>"p_ico_htm.jpg",
	                 "php"=>"p_ico_php.jpg",
	                 "mpeg"=>"screen.png",
	                 "mpg"=>"screen.png",
	                 "wmv"=>"screen.png",
	                 "avi"=>"screen.png",
	                 "unk"=>"p_ico_default.jpg" );
	
	// read file info
	$file_info       = pathinfo($path);
	$extension       = strtolower($file_info["extension"]);
	$file_url        = str_replace(" ", "%20", $path);
    $file_url        = str_replace("&", "%26", $file_url);
	
	// get file and folder name
	$temp_arr        = split ("/", $file_url);
	$temp_file       = $temp_arr[count($temp_arr)-1];
	$temp_dir        = $temp_arr[count($temp_arr)-2];	
	
	if ( strpos($file_url, "http:")===false ) 
	{
		// image names for caching
		$former_cache    = "cache/" . $temp_dir . "/" . $temp_file . "_pimpc.JPG"; 
		$cached_image    = "cache/" . $temp_dir . "/" . $temp_file . "_cache.JPG";	
	}
	else
	{
	    $cache_arr       = urlinfo($path);
		$former_cache    = "cache/" . $cache_arr["path"] . "/" . $cache_arr["filename"] . "_pimpc.JPG"; 
		$cached_image    = "cache/" . $cache_arr["path"] . "/" . $cache_arr["filename"] . "_cache.JPG";	
	}
	
	// delete any old cached images
	if (file_exists($former_cache)) 
	{ 
	    unlink ($former_cache);
	}
	 
	// check to see if a cached image exists
	if (file_exists($cached_image)) 
	{
	   /* DEBUG DATA */ addmetric ("opening cached image");
	    $img_result = imagecreatefromjpeg($cached_image); 
	   /* DEBUG DATA */ addmetric ("cached image open");
	} 
	else 
	{ 
	    /* DEBUG DATA */ addmetric ("opening new image");
		if (strpos(strtolower($file_url), ".jpg")>0) 
		{
			 $img_result = imagecreatefromjpeg($file_url);
		} 
		else if (strpos(strtolower($file_url), ".png")>0) 
		{
			 $img_result = imagecreatefrompng($file_url);
		} 
		else if (strpos(strtolower($file_url), ".gif")>0) 
		{
			 $img_result = imagecreatefromgif($file_url);
		} 
		// attempt to look up icon if this is not an image
		else 
		{ 		
			$img_result = imagecreatetruecolor(132, 132); 
			$bg = imagecolorallocate($img_result, 255, 255, 255); 
			$tc = imagecolorallocate($img_result, 255, 255, 0); 
			$wc = imagecolorallocate($img_result, 190, 190, 190); 
			$bc = imagecolorallocate($img_result, 0, 0, 0); 
			imagefill($img_result, 0, 0, $bg);
			
			$img_temp   = imagecreatefromfile("images/".$icons[array_key_exists($extension,$icons)?$extension:"unk"]); 
			imagecopymerge ($img_result,$img_temp,16,16,0,0,imagesx($img_temp),imagesy($img_temp),100);
			imagedestroy ($img_temp);			 
		}
		
		// if this is a remote file, cache the image
		if ( ! (strpos($file_url, "http:")===false) ) 
		{   
			
			// look up remote thumbnail image
			$img_temp = @imagecreatefromgif($file_url.".gif");
			if ($img_temp) 
			{ // if there is a thumbnail on the server, use it to make a thumbnail here
			 
				imagefill($img_result, 0, 0, $bg); 
				$old_image_width  = imagesx($img_temp);
				$old_image_height = imagesy($img_temp); 
				$new_image_height = 132 / ($old_image_width/$old_image_height); // resize by width  
				imagecopyresized ($img_result, $img_temp, 0, (132-$new_image_height)/2, 0, 0, 132, $new_image_height, $old_image_width, $old_image_height);
				imagedestroy ($img_temp);
				
				$char_left = 6;
				$char_top  = 70; 
				// write the file name on the thumbnail
				for ($z=0;$z<strlen($temp_file);$z++) 
				{ 
					$this_char = substr($temp_file, $z, 1);
					imagestring( $img_result, 1, $char_left+1, $char_top+1, $this_char, $bc);
					imagestring( $img_result, 1, $char_left, $char_top, $this_char, $bg);
					$char_left += imagefontwidth(1);
					if ($char_left >= 125) 
					{
						$char_left = 6;
						$char_top += 10;
					}
				}
				border ($img_result, 0, 0, 131, 131, $wc, $wc); 			 
			} 
			
	        /* DEBUG DATA */ addmetric ("caching http image");
			
			
			
			$path_to_picture = $cache_arr["path"];
			$path_arr  = explode ("/", $path_to_picture);
			$temp_dir = "";
			
			for ($z=0;$z<count($path_arr);$z++)
			{
				// create a folder if there isnt one
				$temp_dir .= $path_arr[$z] . "/";
				if ( ! is_dir("cache/" . $temp_dir) ) 
				{
					mkdir("cache/" . $temp_dir);  
				}
			}
			
			// save cached image
			imagejpeg($img_result, $cached_image, 100);			 
			
			// write metric information on the image AFTER saving
			$bg = imagecolorallocate($img_result, 0, 0, 66);  
			$bc = imagecolorallocate($img_result, 255, 255, 0);  
			 
			$img_temp = @imagecreatefromjpeg("images/logo.jpeg");
			if ($img_temp) 
			{
			    imagecopy($img_result, $img_temp, 4, imagesy($img_result)-28, 0, 0, imagesx($img_temp), imagesy($img_temp));
				imagedestroy ($img_temp);
			} 
			 
			imagestring($img_result, 4, 31, imagesy($img_result)-20, "Cached ".date("M d, Y")." ".filesize($cached_image)." bytes", $bg);
			imagestring($img_result, 4, 30, imagesy($img_result)-21, "Cached ".date("M d, Y")." ".filesize($cached_image)." bytes", $bc);
		}  
	}  
	return $img_result;
}



function colorparse ($f_c) 
{
	sscanf($f_c, "%2x%2x%2x", $red, $green, $blue);
	$f_c = array($red,$green,$blue);
    return $f_c;
}

function WriteToFile($path, $content) 
{
  if(file_exists($path))  unlink ($path);
	$fp = fopen($path, 'w');
	fwrite($fp, $content);
	fclose($fp);  
}

?>